﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using OPTFleet.Data;

namespace OPTFleet
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            // Initialization of window components
            InitializeComponent();
        }


        private void loginButton_Click(object sender, EventArgs e)
        {
            // Check for 0x0
            if (usernameTextBox.Text.Equals("") || passwordTextBox.Text.Equals("")) return;

            loginButton.Enabled = false;
            loginButton.FlatStyle = FlatStyle.Flat;

            // Login
            CamadaDados cd = new CamadaDados();
            Object[] dados = new Object[2];
            dados[0] =  usernameTextBox.Text;
            dados[1] = passwordTextBox.Text;
            int ret = (int)cd.OperacaoDados(CamadaDados.OP_LOGIN, dados);

            // Invalid login
            if (ret < 0)
            {
                MessageBox.Show("Dados de utilizador inválidos!", "Login inválido", MessageBoxButtons.OK, MessageBoxIcon.Error);
                loginButton.FlatStyle = FlatStyle.Standard;
                loginButton.Enabled = true;
                return;
            }

            loginButton.FlatStyle = FlatStyle.Standard;
            loginButton.Enabled = true;

            // Hide the 'Login' window
            this.Hide();
            usernameTextBox.Clear();
            passwordTextBox.Clear();

            // Start and display the application's main window
            MainWindow mw = new MainWindow(cd,(CamadaDados.permissao)ret,(string)dados[0]);
            this.AddOwnedForm(mw);
            mw.ShowDialog(this);

            // Handle the exiting status of the application ('exit' OR 'logout') accordingly
            if (mw.DialogResult == DialogResult.Cancel)
            {
                this.Close();
            }
            else
            {
                this.Show();
            }
        }

        private void processKeyPressed(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r') loginButton_Click(sender,e);
        }

    }
}
